package com.zx.zxapibackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zx.zxapibackend.annotation.AuthCheck;
import com.zx.zxapibackend.model.domain.User;
import com.zx.zxapicommon.common.BaseResponse;
import com.zx.zxapibackend.common.DeleteRequest;
import com.zx.zxapicommon.model.enums.ErrorCode;
import com.zx.zxapicommon.model.to.Oauth2ResTo;
import com.zx.zxapicommon.model.to.UserRequest;
import com.zx.zxapicommon.utils.ResultUtils;
import com.zx.zxapibackend.constant.UserConstant;
import com.zx.zxapicommon.exception.BusinessException;
import com.zx.zxapibackend.exception.ThrowUtils;
import com.zx.zxapibackend.model.dto.user.*;
import com.zx.zxapicommon.model.vo.LoginUserVO;
import com.zx.zxapibackend.model.vo.UserVO;
import com.zx.zxapibackend.service.UserService;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * 用户接口
 *
 * @author 张旭
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody(required = false) UserRegisterRequest userRegisterRequest, HttpServletRequest
            request) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数不存在");
        }

        long result = userService.userRegister(userRegisterRequest, request);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request, HttpServletResponse response) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        LoginUserVO loginUserVO = userService.userLogin(userAccount, userPassword, request, response);
        return ResultUtils.success(loginUserVO);
    }


    /**
     * 获取全站用户数
     *
     * @return
     */
    @GetMapping("/getActiveUser")
    public BaseResponse getActiveUser() {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("isDelete", "0");
        long count = userService.count(userQueryWrapper);
        return ResultUtils.success(count);
    }


    @ApiOperation("用户注销")
    @GetMapping("/logoutSuccess")
    public BaseResponse logoutSuccess(HttpServletResponse response) {
        return ResultUtils.success("退出成功！");
    }


    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(user));
    }


    @ApiOperation("验证用户登录状态")
    @PostMapping("/checkUserLogin")
    public BaseResponse checkUserLogin(HttpServletRequest request, HttpServletResponse response) {
        return userService.checkUserLogin(request, response);
    }

    @PostMapping("/checkLogin")
    public BaseResponse checkLogin(HttpServletRequest request, HttpServletResponse response) {

        return userService.checkUserLogin(request, response);
    }

    /**
     * 创建用户
     *
     * @param userAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest, HttpServletRequest request) {
        if (userAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());
    }

    /**
     * 删除用户
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新用户
     *
     * @param userUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest,
                                            HttpServletRequest request) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取用户（仅管理员）
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUserById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 根据 id 获取包装类
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserVO> getUserVOById(long id, HttpServletRequest request) {
        BaseResponse<User> response = getUserById(id, request);
        User user = response.getData();
        return ResultUtils.success(userService.getUserVO(user));
    }


    /**
     * 分页获取用户封装列表
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list/page")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Page<UserVO>> listUserVOByPage(UserQueryRequest userQueryRequest,
                                                       HttpServletRequest request) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);

        return userService.listUserByPage(userQueryRequest);
    }


    // endregion

    /**
     * 更新个人信息
     *
     * @param userUpdateMyRequest
     * @param request
     * @return
     */
    @PostMapping("/update/my")
    public BaseResponse<Boolean> updateMyUser(@RequestBody UserUpdateMyRequest userUpdateMyRequest,
                                              HttpServletRequest request) {
        if (userUpdateMyRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        User user = new User();
        BeanUtils.copyProperties(userUpdateMyRequest, user);
        user.setId(loginUser.getId());
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    @ApiOperation("发送手机短信验证码")
    @GetMapping("/captcha")
    public BaseResponse<String> sendCode(@RequestParam("mobile") String phoneNum) {
        userService.sendCode(phoneNum);

        //直接返回成功信息，异步发送短信
        return ResultUtils.success("发送短信验证码成功！");
    }

    @ApiOperation("生成图形验证码")
    @GetMapping("/getCaptcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) {
        userService.getCaptcha(request, response);
    }

    @ApiOperation("通过第三方登录")
    @PostMapping("/oauth2/login")
    public BaseResponse oauth2Login(@RequestBody Oauth2ResTo oauth2ResTo, @RequestParam("type") String type , HttpServletResponse httpServletResponse){
        return userService.oauth2Login(oauth2ResTo,type,httpServletResponse);
    }

    @ApiOperation("用户通过手机号进行登录")
    @PostMapping("/loginBySms")
    public BaseResponse loginBySms(@RequestBody UserLoginBySmsRequest loginBySms , HttpServletResponse response){
        return userService.loginBySms(loginBySms,response);
    }


    @ApiOperation("获取GitHub的stars")
    @GetMapping("/getGithubStars")
    public BaseResponse getGithubStars(){
        return userService.getGithubStars();
    }

    @ApiOperation("绑定用户手机号")
    @PostMapping("/bindPhone")
    public BaseResponse bindPhone(UserBindPhoneRequest userBindPhoneRequest,HttpServletRequest request){
        return userService.bindPhone(userBindPhoneRequest,request);
    }

    @ApiOperation("修改用户密码")
    @PostMapping("/updateUserPass")
    public BaseResponse updateUserPass(String password,HttpServletRequest request){
        return userService.updateUserPass(password,request);
    }

    @ApiOperation("忘记密码部分-验证手机号和验证码输入是否正确")
    @PostMapping("/authPassUserCode")
    public BaseResponse authPassUserCode(String code,HttpServletRequest request){
        return userService.authPassUserCode(code,request);
    }

    @ApiOperation("忘记密码请求第二步，发送验证码")
    @PostMapping("/sendPassUserCode")
    public BaseResponse sendPassUserCode(HttpServletRequest request) throws NoSuchAlgorithmException {
        return userService.sendPassUserCode(request);
    }


    @ApiOperation("用户忘记密码，返回用户注册时的手机号")
    @PostMapping("/getpassusertype")
    public BaseResponse getPassUserType(String username,HttpServletResponse response){
        return userService.getPassUserType(username,response);
    }



}
